import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { Toast } from 'antd-mobile';
// import * as process from 'process';
import { AUTH_TOKEN } from './constants';

// let uri = '//www.coderzsc.top/nest/graphql';
const uri = '//localhost:3001/graphql';
// if (process.env.NODE_ENV === 'production') {
//   //   uri = 'https://water-drop.yondu.vip';
//   uri = 'http://www.coderzsc.top';
// }
const httpLink = createHttpLink({
  uri,
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem(AUTH_TOKEN);
  return {
    headers: {
      ...headers,
      Authorization: token ? `Bearer ${token}` : '',
    },
  };
});

/**
 * 统一处理接口报错---graphQL
 */
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    Toast.show({ content: graphQLErrors[0].message });
    graphQLErrors.forEach((item) => {
      if (item.message === 'Unauthorized') {
        Toast.clear();
        Toast.show({ content: '登录失效, 请重新登录' });
      }
    });
  }
  if (networkError) {
    Toast.clear();
    Toast.show({ content: networkError.message });
  }
});

/**
 * 引入errorLink
 * 初始化apolloClient
 */
export const client = new ApolloClient({
  link: errorLink.concat(authLink.concat(httpLink)),
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'no-cache',
    },
  },
  cache: new InMemoryCache({
    addTypename: false,
  }),
});
